import { CompileUtil } from "../../ADCore/MVVM/CompileUtil";
import TextAncient from "../ExtendComponent/TextAncient";
import { ICompile, IVMMain } from "../../ADCore/Interfaces/IMVVM";
import VMForTransfer from "../../ADCore/MVVM/VMForTransfer";


export default class RenderUtil {

    textUpdater(node, value) {
        RenderUtil.changeTextNode(node,value).text = typeof value === 'undefined' ? '' : value;
    }
    forUpdater(node, value, oldValue, attrName: VMForTransfer, vm: IVMMain) {
        //监听渲染值
        var isNull = typeof value === 'undefined';
        if (!isNull && !node.renderHandler) {
            //给与容器绑定值
            node.renderHandler = Laya.Handler.create(this, (cell, index) => {
                var bindValue = value[index];
                var bindOldValue = null;
                if (oldValue) bindOldValue = oldValue[index];
                if (attrName.watch)
                    bindValue = attrName.watch.runWith([bindValue, bindOldValue, cell, index]);
                cell.value = bindValue;
                vm[attrName.item] = bindValue;
                vm.$icompile.compileElement(cell);
            }, null, false);
            node.array = isNull ? '' : value;
        }
        else {
            node.array = isNull ? '' : value;
        }

    }
    displayUpdater(node, value) {
        if (typeof value !== 'undefined') {
            node.visible = value;
        }
    }
    classUpdater() { }

    attrUpdater(node, value, old, attrName) {
        node = RenderUtil.changeTextNode(node, value);  
        typeof(node[attrName])!="undefined" && (node[attrName] = (typeof value === 'undefined' ? '' : value));
    }
    modelUpdater(node, value, oldValue) {
        //不对当前操作input进行渲染操作
        if (CompileUtil.$elCurrent === node) {
            return false;
        }
        CompileUtil.$elCurrent = undefined;
        node.text = typeof value === 'undefined' ? '' : value;
    }

    /**
 * 将节点改为可识别文本节点
 */
    static changeTextNode(node, value): any {
        var nodeType = node["__proto__"].constructor.name;
        if (nodeType == "Button") {
            if (typeof (value) == "string")
                return node.text;
            else
                return node;
        }
        else if (node.getComponent && node.getComponent(TextAncient)) {
            return node.getComponent(TextAncient);
        }
        else
            return node;
    }
}
